﻿using System;
using System.Collections.Generic;

namespace winS.Unity
{
    /// <summary>
    /// 更新组.
    /// 提供对各类更新函数的管理
    /// </summary>
    public class UpdateGroup
    {
        private bool stopping;

        private readonly List<UpdateHandle> updateHandleList = new List<UpdateHandle>();
        private readonly List<DelayCallHandle> delayCallHandleList = new List<DelayCallHandle>();
        private readonly List<RepeatCallHandle> repeatCallHandleList = new List<RepeatCallHandle>();

        public void Stop()
        {
            stopping = true;
            foreach (var updateHandle in updateHandleList) updateHandle.Stop();
            foreach (var delayCallHandle in delayCallHandleList) delayCallHandle.Stop();
            foreach (var repeatCallHandle in repeatCallHandleList) repeatCallHandle.Stop();
            updateHandleList.Clear();
            delayCallHandleList.Clear();
            repeatCallHandleList.Clear();
            stopping = false;
        }

        public UpdateHandle AddUpdate(Action function)
        {
            return AddUpdate(_ => function());
        }
        public UpdateHandle AddUpdate(Action<float> function)
        {
            UpdateHandle updateHandle = Updater.AddUpdate(function);
            updateHandle.onFinished += () =>
            {
                if (stopping) return;
                updateHandleList.Remove(updateHandle);
            };
            updateHandleList.Add(updateHandle);
            return updateHandle;
        }
        public DelayCallHandle AddDelayCall(float delay, Action function)
        {
            DelayCallHandle delayCallHandle = Updater.AddDelayCall(delay, function);
            delayCallHandle.onFinished += () =>
            {
                if (stopping) return;
                delayCallHandleList.Remove(delayCallHandle);
            };
            delayCallHandleList.Add(delayCallHandle);
            return delayCallHandle;
        }
        public RepeatCallHandle AddRepeatCall(float interval, Action function)
        {
            RepeatCallHandle repeatCallHandle = Updater.AddRepeatCall(interval, function);
            repeatCallHandle.onFinished += () =>
            {
                if (stopping) return;
                repeatCallHandleList.Remove(repeatCallHandle);
            };
            repeatCallHandleList.Add(repeatCallHandle);
            return repeatCallHandle;
        }
    }
}